package cn.wmw.xyy.security;

import cn.wmw.xyy.domain.Login;
import cn.wmw.xyy.domain.Permission;
import cn.wmw.xyy.service.ILoginService;
import cn.wmw.xyy.service.IPermissionService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
@Component
public class LoginUserDetailService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login login = selectByUsername(username);
        if (login != null){
           List<Permission> permissions =  permissionService.selectByLoginId(login.getId());
//            String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired,
//            boolean accountNonLocked, Collection<? extends GrantedAuthority > authorities
            List<SimpleGrantedAuthority> authorities = permissions.stream().map(e -> new SimpleGrantedAuthority(e.getSn())).collect(Collectors.toList());
            return new User(
                login.getUsername(),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                    authorities);
        }
        return null;
    }

    private Login selectByUsername(String username) {
        return loginService.selectOne(new EntityWrapper<Login>().eq("username", username));
    }

}
